<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\View; //模板引擎
use app\common\Base;
use think\facade\Request;
use think\exception\ValidateException;
use app\model\GoodsCat as GoodsCatMod;
use app\validate\GoodsCatVal;

/**
 * @name 商品类型
 */
class GoodsCat extends Base
{
    /**
     * @name 类型列表
     */
    public function list()
    {
        if (request()->isPost()) {
            $list = GoodsCatMod::list();
            return getBack(0, '', $list);
        }
        return View::fetch();
    }

    /**
     * @name 类型添加
     */
    public function add()
    {
        $list = GoodsCatMod::list();
        View::assign('select', grades($list));
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(GoodsCatVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $res = GoodsCatMod::add($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 类型编辑
     */
    public function edit()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $find = GoodsCatMod::find($id);
            View::assign('find', $find);
            $list = GoodsCatMod::list([['id', 'not in', $id]]);
            View::assign('select', grades($list));
        }
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(GoodsCatVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $res = GoodsCatMod::edit($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 类型删除
     */
    public function del()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $res = GoodsCatMod::del($id);
            if ($res == 'success') {
                return getBack(0);
            } else {
                return getBack(3, $res);
            }
        }
    }
}
